package com.hiznu.amap_flutter

import android.content.Context
import androidx.lifecycle.Lifecycle
import com.amap.api.location.AMapLocationClient
import com.amap.api.maps.MapsInitializer
import com.hiznu.amap_flutter.map.AMapPlatformViewFactory
import fl.channel.FlChannelPlugin
import fl.channel.FlEventChannel
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.embedding.engine.plugins.lifecycle.HiddenLifecycleReference
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** AmapFlutterPlugin */
class AmapFlutterPlugin : FlutterPlugin, ActivityAware {
    private var location: AMapLocationHandler? = null
    private var geoFence: AMapGeoFenceHandler? = null
    private var map: AMapMapHandler? = null


    companion object {
        var lifecycle: Lifecycle? = null
        var flEventChannel: FlEventChannel? = null
    }

    override fun onAttachedToEngine(plugin: FlutterPlugin.FlutterPluginBinding) {
        location = AMapLocationHandler(plugin)
        geoFence = AMapGeoFenceHandler(plugin)
        map = AMapMapHandler(plugin)
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        location?.detached()
        geoFence?.detached()
        map?.detached()
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        val reference = binding.lifecycle as HiddenLifecycleReference
        lifecycle = reference.lifecycle
    }

    override fun onDetachedFromActivityForConfigChanges() {
        onDetachedFromActivity()
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        onAttachedToActivity(binding)
    }

    override fun onDetachedFromActivity() {
        lifecycle = null
    }
}
